package com.fingard.dsp.bank.directbank.tzb01;

import com.fingard.net.SftpPortClient;
import org.apache.commons.net.ftp.FTP;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.bankInterface.IReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.ReqQryReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.RetAtsReceipt;
import com.fingard.net.ConnState;
import com.fingard.net.FtpPortClient;
import com.fingard.net.FtpReceiver;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.util.SmbFileUtil;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.io.File;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by F on 2019/4/17.
 * 步骤:
 * 1.配置好前置机 2.发送下载报文到前置软件,前置软件自动下载文件到安装目录,将文件从共享安装目录复制到本地
 * 2.定时任务读去本地文件夹,解析文件并下载回单到本地,上传到ATS共享目录并推送消息
 */
public class TZB01Receipt extends TZB01Base implements IReceipt {
    private String receiptSaveToMainDir = "";

    @Override
    public RetAtsReceipt qryReceipt(ReqQryReceipt p_reqReceipt) throws Exception {
        RetAtsReceipt retAts = new RetAtsReceipt(p_reqReceipt.reqHeader);
        receiptSaveToMainDir = FGBiz.dspCenter.dspSet.receiptMainDir;
        if (StringHelper.hasAnyChar(receiptSaveToMainDir)) {
            if (StringHelper.hasAnyChar(FGBiz.dspCenter.dspSet.receiptShareDir)) {
                if (StringHelper.hasAnyChar(FGBiz.dspCenter.dspSet.receiptPushServerUrl)) {
                    download(p_reqReceipt);
                    retAts.respCode = "0";
                    retAts.respInfo = "后台正在处理中";
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = "DSPSystem未配置回单文件推送地址";
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "DSPSystem未配置回单文件共享目录";
            }
        } else {
            retAts.respCode = "-1";
            retAts.respInfo = "DSPSystem未配置回单文件下载保存主目录";
        }
        retAts.writeRetToATS();
        return retAts;
    }

    private void download(ReqQryReceipt p_reqReceipt) {
        try {
            Calendar tmpCalendarForm = Calendar.getInstance();
            tmpCalendarForm.setTime(p_reqReceipt.getDateFrom());
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_reqReceipt.getDateTo());

            int tmpIntFrom = Integer.valueOf(Format.Date8Format.format(p_reqReceipt.getDateFrom()));
            int tmpIntTo = Integer.valueOf(Format.Date8Format.format(p_reqReceipt.getDateTo()));
            do {
                Calendar tmpCalendarStep = Calendar.getInstance();
                if (DateHelper.compareMonth(tmpCalendarForm, tmpCalendarTo) == -1) {
                    tmpCalendarStep.setTime(tmpCalendarForm.getTime());
                    tmpCalendarStep.set(Calendar.DAY_OF_MONTH, tmpCalendarForm.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    tmpCalendarStep.setTime(tmpCalendarTo.getTime());
                }
                int tmpIntStep = Integer.valueOf(Format.Date8Format.format(tmpCalendarStep.getTime()));
                XmlTextWriter xmlWriter = new XmlTextWriter();
                TZB01Header header = new TZB01Header();
                header.tr_code = "544003";
                header.req_no = p_reqReceipt.reqHeader.reqSeqID;
                writeCommonHeader(xmlWriter, header);
                xmlWriter.writeEndElement();
                xmlWriter.writeStartElement("body");
                // 1	acno	账号	C20	M
                xmlWriter.writeElementString("acno", p_reqReceipt.actNum);
//                 2	start_date	开始日期	C8	M
                xmlWriter.writeElementString("start_date", "" + tmpIntFrom);
//                 3	end_date	结束日期	C8	M
                xmlWriter.writeElementString("end_date", "" + tmpIntStep);
                xmlWriter.writeEndDocument();
                //拼接报文, 统计字节长度
                int length = xmlWriter.toXmlString().getBytes(getCharset()).length + 2;
                String head = String.format("%-10s", length + "") + "00";
                String[] bankResult = sendToBank(head + xmlWriter.toXmlString());
                if (bankResult[0].length() == 0) {
                    StringBuilder tmpBkMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1].substring(12), tmpBkMsg);
                    if (tmpBkReader != null) {
                        String succFlag = tmpBkReader.getFirstText("/ap/head/succ_flag");
                        String retCode = tmpBkReader.getFirstText("/ap/head/ret_code");
                        String retInfo = tmpBkReader.getFirstText("/ap/head/ret_info");
                        if (succFlag.equals("0") && retCode.equals("0000")) {
                            String fileName = tmpBkReader.getFirstText("/ap/body/file_name");
                            if (StringHelper.hasAnyChar(fileName)) {
                                //将文件保存在
                                String localpath = FGBiz.dspCenter.dataDirPath + File.separator + "datafile" + File.separator + bankFront.bankCode + File.separator +
                                        "receiptdatafile" + File.separator + Format.Date8Format.format(new Date()) + File.separator +
                                        p_reqReceipt.actNum;
                                String receiptDownType = getBankConfig().getValueAsString("receiptDownType");
                                if ("sftp".equals(receiptDownType)) {
                                    //Sftp方式
                                    SftpPortClient sftpPortClient = null;
                                    try {
                                        FtpSet ftpSet = bankFront.getFtpSet("receipt");
                                        ftpSet.downDir = StringHelper.trimEnd(ftpSet.downDir, "/") + "/";
                                        WriteBankLogLn("SFTP下载地址" + ftpSet.serverIP + ":" + ftpSet.port);

                                        sftpPortClient = new SftpPortClient(ftpSet);
                                        WriteBankLogLn("下载到本地目录为："+localpath);
                                        WriteBankLogLn("sftp目录下文件名为："+ fileName);
                                        FtpReceiver ftpReceiver = sftpPortClient.downloadFileByName("" ,localpath,fileName);
                                        if(ftpReceiver.isCompleted){
                                            WriteBankLogLn("下载成功，下载路径为："+localpath+"文件名为"+fileName);
                                        }else{
                                            WriteBankLogLn("下载失败，文件名为"+fileName);
                                        }
                                    } catch (Exception ex) {
                                        ex.printStackTrace();
                                        WriteBankLogLn(ex);
                                    } finally {
                                        if (sftpPortClient != null) {
                                            sftpPortClient.disconnect();
                                        }
                                    }
                                } else if ("ftp".equals(receiptDownType)) {
                                    FtpSet ftpSet = bankFront.getFtpSet("receipt");
                                    FtpPortClient client = new FtpPortClient(ftpSet);
                                    FtpReceiver ftpReceiver = client.downloadFile(fileName, localpath);
                                    if (!ftpReceiver.isCompleted) {
                                        WriteBankLogLn(ftpReceiver.connMsg);
                                    } else if (ConnState.FAIL.equals(ftpReceiver.connState)) {
                                        WriteBankLogLn("下载失败");
                                    } else {
                                        WriteBankLogLn("下载成功");
                                    }
                                } else {
                                    //共享目录方式
                                    if (StringHelper.hasAnyChar(bankFront.bankReceiptMainDir)) {
                                        StringBuilder smbSb = new StringBuilder();
                                        SmbFileUtil.smbDownload(localpath, bankFront.bankReceiptMainDir, fileName, smbSb);
                                    } else {
                                        throw new Exception("请配置银行前置机回单目录");
                                    }
                                }
                            } else {
                                WriteBankLogLn(tmpBkReader.getFirstText("/ap/head/ext_info"));
                            }
                        } else {
                            WriteBankLogLn(retInfo);
                        }
                    } else {
                        WriteBankLogLn(tmpBkMsg.toString());
                    }
                } else {
                    WriteBankLogLn(bankResult[1]);
                }
                tmpCalendarForm.setTime(tmpCalendarStep.getTime());
                tmpCalendarForm.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntFrom = Integer.valueOf(Format.Date8Format.format(tmpCalendarForm.getTime()));
            } while (tmpIntFrom <= tmpIntTo);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
